package com.example.librarymanagementsystembackend.usermanagement.controller;

import com.example.librarymanagementsystembackend.usermanagement.entity.UserProfile;
import com.example.librarymanagementsystembackend.usermanagement.entity.UserProfileDTO;
import com.example.librarymanagementsystembackend.usermanagement.entity.UserRegisterDTO;
import com.example.librarymanagementsystembackend.usermanagement.service.UserService;
import com.example.librarymanagementsystembackend.utils.FileUtils;
import com.example.librarymanagementsystembackend.utils.InvalidRequestException;
import com.example.librarymanagementsystembackend.usermanagement.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;

@RestController
@CrossOrigin(origins = "http://localhost:8080")  //和Vue框架跨域连接
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private FileUtils fileUtils;

    /**
     * 用户注册
     */
    @PostMapping("/register")
    public String register(@RequestBody UserRegisterDTO dto) {
        try {
            userService.userRegister(dto);
            return "用户注册成功";
        } catch (InvalidRequestException e) {
            throw new InvalidRequestException("注册失败(" + e.getMessage() + ")");
        }
    }

    /**
     * 获取用户信息 通过 ID
     */
    @GetMapping("/{id}")
    public User getUserById(@PathVariable int id) {
        try {
            return userService.getUserById(id);
        } catch (InvalidRequestException e) {
            throw new InvalidRequestException("获取用户信息失败( " + e.getMessage() + ")");
        }
    }

    /**
     * 更新用户资料
     */
    @PutMapping("/{userId}/profile")
    public String updateUserProfile(
            @PathVariable Integer userId,
            @RequestBody UserProfileDTO dto) {
        try {
            userService.updateUserProfile(userId, dto);
            return "用户资料更新成功";
        } catch (InvalidRequestException e) {
            throw new InvalidRequestException("用户资料更新失败( " + e.getMessage() + ")");
        }
    }

    /**
     * 删除用户 通过 ID
     */
    @DeleteMapping("/{id}")
    public String deleteById(@PathVariable int id) {
        try {
            userService.deleteUserById(id);
            return "用户删除成功";
        } catch (InvalidRequestException e) {
            throw new InvalidRequestException("用户删除失败( " + e.getMessage() + ")");
        }
    }

    /**
     * 获取全部用户
     */
    @GetMapping("/all")
    public List<User> findAllUsers() {
        return userService.findAllUsers();
    }



    /**
     * 获取用户头像 通过 用户ID
     * 获取服务器储存的用户头像
     *
     * 返回 实体用户头像文件
     */
    @GetMapping("/{id}/avatar")
    public ResponseEntity getUserAvatarByUserId(@PathVariable int id) throws IOException {
        // 获取用户头像路径
        String path = userService
                .findProfileByUserId(id)
                .getAvatarUrl();

        Resource resource = fileUtils.getFile(path);

        // 检查文件是否存在
        if (!resource.exists()) {
            throw new InvalidRequestException(404, "文件不存在");
        }

        // 判断文件类型
        String mimeType = Files.probeContentType(Paths.get(path));
        if (mimeType == null) {
            mimeType = "application/octet-stream";
        }

        // 设置响应头
        return ResponseEntity.ok()
                .contentType(MediaType.parseMediaType(mimeType))
                .body(resource);
    }
}